#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>

#define SERVER_PORT 8080
#define SERVER_ADDR "192.168.0.104"


int main(int argc, char *argv[]) 
{
    int ret;
    int serverfd, clientfd;
    struct sockaddr_in server_addr, client_addr;
    char buf[512];
    char client_ip_str[20] = {0};
    int c_addrlen = sizeof(client_addr);
    
    // 打开套接字
    serverfd = socket(AF_INET, SOCK_STREAM, 0);
    if (serverfd < 0) {
        printf("socket error\n");
        exit(EXIT_FAILURE);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    inet_pton(AF_INET, SERVER_ADDR, &server_addr);

    // 绑定
    ret = bind(serverfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (ret < 0) {
        printf("bind errno \n");
        close(serverfd);
        exit(EXIT_FAILURE);
    }

    // 监听
    ret = listen(serverfd, 50);
    if (ret < 0) {
        printf("listen error\n");
        close(serverfd);
        exit(EXIT_FAILURE);
    }

    // 等待连接
    clientfd = accept(serverfd, (struct sockaddr *)&client_addr, &c_addrlen);
    if (clientfd < 0) {
        printf("accept error\n");
        close(serverfd);
        exit(EXIT_FAILURE);
    }
    
    inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, client_ip_str, sizeof(client_ip_str));
    printf("已连接  ip：%s\n", client_ip_str);
    while(1) {
        memset(buf, 0, sizeof(buf));

        ret = recv(clientfd, buf, sizeof(buf), 0);
        if (ret < 0) {
            printf("reve error\n");
            close(clientfd);
            exit(EXIT_FAILURE);
        }

        printf("接收到的数据为：%s\n", buf);

        if (strncmp(buf, "exit", 4) == 0) {
            close(clientfd);
            break;
        }
    }

    close(serverfd);
    exit(EXIT_SUCCESS);
}

